package mo.leetcode_hot;

public class L79 {

    private final int[][] directions = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

    public boolean exist(char[][] board, String word) {
        int m = board.length, n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                boolean contains = check(board, visited, i, j, word, 0);
                if (contains) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean check(char[][] board, boolean[][] visited, int i, int j, String work, int k) {
        if (board[i][j] != work.charAt(k)) {
            return false;
        } else if (k == work.length() - 1) {
            return true;
        }
        visited[i][j] = true;
        boolean result = false;
        for (int l = 0; l < directions.length; l++) {
            int nextI = i + directions[l][0];
            int nextJ = j + directions[l][1];
            if (nextI >=0 && nextI < board.length && nextJ >= 0 && nextJ < board[0].length && !visited[nextI][nextJ]) {
                if (check(board, visited, nextI, nextJ, work, k+1)) {
                    result = true;
                    break;
                }
            }
        }
        visited[i][j] = false;
        return result;
    }

}
